package com.skz.oidcclientdemo;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.support.BasicAuthenticationInterceptor;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
@RequestMapping("/dapeng")
@Slf4j
public class SsoController {
    private static final String TOKEN_URL = "http://localhost:8080/auth/realms/springdemo/protocol/openid-connect/token";
    private static final String REDIRECT_URI = "http://localhost:9090/dapeng/callback";
    private static final String CLIENT_ID = "pc";
    private static final String SECRET = "3860e7b0-403f-4156-8f53-bb07461578a4";

    @GetMapping("/callback")
    public String token(@RequestParam String code, HttpSession session) {
        RestTemplate restTemplate = new RestTemplate();
        //basic认证
        restTemplate.getInterceptors().add(new BasicAuthenticationInterceptor(CLIENT_ID, SECRET));
        //表单提交
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/x-www-form-urlencoded");
        //参数
        MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
        requestBody.add("grant_type", "authorization_code");
        requestBody.add("code", code);
        requestBody.add("redirect_uri", REDIRECT_URI);
        HttpEntity<MultiValueMap> entity = new HttpEntity<>(requestBody, headers);
        //请求
        ResponseEntity<JSONObject> tokenResponse = restTemplate.postForEntity(TOKEN_URL, entity, JSONObject.class);
        String accessToken = tokenResponse.getBody().getString("access_token");
        String refreshToken = tokenResponse.getBody().getString("refresh_token");
        String idToken = tokenResponse.getBody().getString("id_token");
        session.setAttribute("access_token", accessToken);
        session.setAttribute("refresh_token", refreshToken);
        session.setAttribute("id_token", idToken);
        return "/";
    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest request) {
        request.getSession().invalidate();
        return "/";
    }
}